package controllers

import (
	"context"
	beego "github.com/beego/beego/v2/server/web"
	"net/http"
	"strconv"
	"time"
	"user/common"
	"user/models"
)

type LoginController struct {
	beego.Controller
}

func (this *LoginController) Login() {
	mobile := this.GetString("mobile")
	password := this.GetString("pwd")
	data, err := models.Logins(mobile)
	if err != nil {
		this.Data["json"] = map[string]interface{}{
			"code":    http.StatusCreated,
			"message": err.Error(),
		}
		this.ServeJSON()
		return
	}

	var Countkey = "count:" + mobile
	if data.Password != password {
		redis := common.ConnectRedis()
		count, _ := strconv.Atoi(redis.Get(context.Background(), Countkey).Val())
		if count >= 3 {
			this.Data["json"] = map[string]interface{}{
				"code":    http.StatusCreated,
				"message": "今日不可再次登录",
			}
			this.ServeJSON()
			return
		}
		redis.Incr(context.Background(), Countkey)
		redis.Expire(context.Background(), Countkey, 10*time.Minute)
		this.Data["json"] = map[string]interface{}{
			"code":    http.StatusCreated,
			"message": "密码错误",
		}
		this.ServeJSON()
		return
	}
	this.Data["json"] = map[string]interface{}{
		"code":    http.StatusOK,
		"message": "登陆成功",
	}
	//保存用户的登录状态
	this.GetSession(data)
	this.ServeJSON()
	return
}
